package jsp;

import entity.User;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.*;
import java.util.Random;

@WebServlet("*.code")
public class CodeServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        switch (path){
            case "/show.code":
                showCode(req,resp);
                break;
            case "/login.code":
                login(req,resp);
                break;
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        // 从session中获取图片中的验证码
        String image = (String) req.getSession().getAttribute("code");
        // 先比较验证码
        if(!image.equals(code)){
            req.setAttribute("loginMsg","验证码不正确");
            req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
        } else{
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            User user = null;
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8", "root", "root");
                String sql = new StringBuffer()
                        .append(" select id,username,password,phone,address ")
                        .append(" from t_user ")
                        .append(" where username = ? ")
                        .append(" and password = ? ")
                        .toString();
                ps = conn.prepareStatement(sql);
                ps.setString(1, username);
                ps.setString(2, password);
                rs = ps.executeQuery();
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setPhone(rs.getString("phone"));
                    user.setAddress(rs.getString("address"));
                    // 登录成功之后,将查询到的用户信息保存到session中
                    req.getSession().setAttribute("user",user);
                    // 登录成功之后,一般表示当前用户相关功能块结束了,进入下一个功能块
                    // 对于这种场景,一般使用重定向
                    resp.sendRedirect(req.getContextPath()+"/jsp/main.jsp");
                    return;
                }
                // 如果没有进入分支,说明没有查询到结果,即:用户名或密码错误
                // 返回错误信息
                req.setAttribute("loginMsg","用户名或密码错误");
                req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    protected void showCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Random random = new Random();
        // 在内存中定义一个画板
        BufferedImage image = new BufferedImage(50, 25, BufferedImage.TYPE_INT_RGB);
        // 获取画板中的画笔
        Graphics graphics = image.getGraphics();
        // 定义画笔填充的矩形区域
        graphics.fillRect(0, 0, 50, 25);
        // 设置绘制的内容的颜色,设置随机色
        graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        // 设置绘制的内容的字体
        graphics.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, 18));
        // 设置图片的内容,随机生成四位数字或者英文字母
        String s = "0123456789qwertyuioplkjhgfdsazxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        String code = buffer.toString();
        System.out.println("验证码:" + code);
        // 将验证码的值存储到session中,便于校验
        req.getSession().setAttribute("code", code);
        // 将内容绘制到画板上
        graphics.drawString(code, 5, 18);
        // 输出验证码图片
        ImageIO.write(image, "JPEG", resp.getOutputStream());
    }
}
